package cn.hicard.auth.web.ctrl;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hicard.auth.entity.MgRoleinfo;
import cn.hicard.auth.entity.MgUserRole;
import cn.hicard.auth.entity.MgUserRoleId;
import cn.hicard.auth.entity.MgUserinfo;
import cn.hicard.auth.service.RoleinfoService;
import cn.hicard.auth.service.UserinfoService;
import cn.hicard.auth.web.AuthFilter;
import cn.hicard.core.Page;
import cn.hicard.core.PageResult;
import cn.hicard.core.Where;
import cn.hicard.risk.entity.SysDept;
import cn.hicard.risk.service.sys.DeptService;
import cn.hicard.util.DateHelp;

import com.sun.org.apache.xml.internal.security.utils.Base64;

@Controller
@RequestMapping("/auth/user")
public class UserinfoCtrl {

	/** 用户类型：超级管理员 */
	public static final String UT_SUPER_ADMIN = "3";
	/** 用户类型：管理员 */
	public static final String UT_ADMIN = "2";
	/** 用户类型：超级管理员 */
	public static final String UT_GENERAL_USER = "1";
	
	@Autowired
	private UserinfoService userinfoService;
	@Autowired
	private DeptService deptService;

	/************** ↓↓↓↓  用户自身的数据管理  ↓↓↓↓ **************/
	
	/**
	 * 加载页面的所有初始信息，使用默认路径
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public String search(HttpSession session, 
			@RequestParam(required=false,defaultValue="1") int index, 
			@RequestParam(required=false,defaultValue="20") int size, 
			@RequestParam(required=false) String loginid,
			@RequestParam(required=false) String enabled,
			@RequestParam(required=false) Integer pkDept,
			ModelMap map) throws Exception {
		MgUserinfo logonUser = (MgUserinfo)session.getAttribute(AuthFilter.LOGON_USER);

		// 查询条件
		Where where=new Where(MgUserinfo.class, Where.MODE_NOT_CHECK);
		where.addLike("loginid", loginid);
		where.addEqual("enabled", enabled);
		where.addEqual("dept.pkDept", pkDept);
		// 超级管理员查全部、普通管理员不能查到[超级管理员]用户、一般用户无法访问
		if( ! UT_SUPER_ADMIN.equals(logonUser.getUsertype())){
			where.addNotEqual("usertype", UT_SUPER_ADMIN);
		}
		// 分页条件，Hibernate查询分页时页码从0开始
		Page page = new Page(index-1, size);		
		PageResult<MgUserinfo> pr = userinfoService.search(where, page);		
		map.addAttribute("list", pr.getDataList());
		map.addAttribute("totalcount", pr.getResultCount());
		// 部门
		List<SysDept> depts = deptService.getAll();
		map.addAttribute("depts", depts);
		
		return "/auth/user";
	}
	
	@ResponseBody
	@RequestMapping("/exists")
	public String exists(@RequestParam String loginid) throws Exception{
		if(userinfoService.existLoginid(loginid)){
			return "1";
		}else{
			return "0";
		}
	}
	

	/**
	 * 前往新增页面
	 * @return
	 */
	@RequestMapping("/toadd")
	public String toadd(ModelMap map)throws Exception{
		map.addAttribute("userinfo", new MgUserinfo());
		// 部门
		List<SysDept> depts = deptService.getAll();
		map.addAttribute("depts", depts);
		return "/auth/useredit";
	}
	
	/**
	 * 前往修改页面
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/tomod")
	public String toupd(ModelMap map, @RequestParam int pkUserinfo) throws Exception{
		MgUserinfo userinfo = userinfoService.getByPk(pkUserinfo);
		map.addAttribute("userinfo", userinfo);
		// 部门
		List<SysDept> depts = deptService.getAll();
		map.addAttribute("depts", depts);
		return "/auth/useredit";
	}
	
	/**
	 * 保存
	 * @param pkUserinfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/save", method=RequestMethod.POST)
	public String save(HttpSession session,@ModelAttribute("userinfo") MgUserinfo userinfo) throws Exception{
		MgUserinfo logonUser = (MgUserinfo)session.getAttribute(AuthFilter.LOGON_USER);
		if( UT_SUPER_ADMIN.equals(userinfo.getUsertype()) && ! UT_SUPER_ADMIN.equals(logonUser.getUsertype())){
			throw new Exception("只有[超级管理员]才能添加[超级管理员]用户");
		}
		MessageDigest md = MessageDigest.getInstance("MD5");
		String password = Base64.encode(md.digest("123456".getBytes()));
		userinfo.setPassword(password);
		userinfoService.save(userinfo);
		return "redirect:/auth/user.do";
	}

	/**
	 * 普通的更新用户，一些特别字段的更新会引起麻烦，不允许更新这些字段，如loginid,password
	 * @param pkUserinfo
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(HttpSession session, @ModelAttribute("userinfo") MgUserinfo userinfo) throws Exception{
		MgUserinfo logonUser = (MgUserinfo)session.getAttribute(AuthFilter.LOGON_USER);
		if( UT_SUPER_ADMIN.equals(userinfo.getUsertype()) && ! UT_SUPER_ADMIN.equals(logonUser.getUsertype())){
			throw new Exception("只有[超级管理员]才能将其它用户修改为[超级管理员]用户");
		}
		MgUserinfo oldUser = userinfoService.getByPk(userinfo.getPkUserinfo());
		userinfo.setLoginid(oldUser.getLoginid());
		userinfo.setPassword(oldUser.getPassword());
		userinfoService.update(userinfo);
		return "redirect:/auth/user.do";
	}
	
	/**
	 * 删除用户
	 * @param pkUserinfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public String delete(@RequestParam("pkUserinfo")int pkUserinfo) throws Exception{
		userinfoService.delete(pkUserinfo);
		return "redirect:/auth/user.do";
	}
		
	/**
	 * 重置密码为123456
	 * @param pkUserinfo
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/restpwd")
	public String restpwd(@RequestParam("pkUserinfo")int pkUserinfo) throws Exception{
		MgUserinfo userinfo = userinfoService.getByPk(pkUserinfo);
		MessageDigest md = MessageDigest.getInstance("MD5");
		String password = Base64.encode(md.digest("123456".getBytes()));
		userinfo.setPassword(password);
		userinfoService.update(userinfo);
		return "redirect:/auth/user.do";
	}
	
	/**
	 * 刷新页面显示
	 * @return
	 */
	@RequestMapping("/refresh")
	public String refresh(){		
		return "redirect:/auth/user.do";
	}

	/************** ↑↑↑↑  用户自身的数据管理  ↑↑↑↑ **************/
	
	
	
	
	/************** ↓↓↓↓  用户分配资源  ↓↓↓↓ **************/
	@Autowired
	private RoleinfoService roleinfoService;
	
	/**
	 * 加载用户分配角色数据
	 * @param pkUserinfo
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/allotrole")
	public String loadAllotRole(@RequestParam("pkUserinfo")int pkUserinfo,
			HttpSession session,
			ModelMap map) throws Exception{
		MgUserinfo logonUser = (MgUserinfo)session.getAttribute(AuthFilter.LOGON_USER);
		// (1)分配的用户对象本身
		MgUserinfo user = userinfoService.getByPk(pkUserinfo);
		map.addAttribute("user", user);
		// (2)系统现存的可分配的角色
		List<MgRoleinfo> roles;
		// A.如果是超级管理员，则可以分配所有的角色
		if(UT_SUPER_ADMIN.equals(logonUser.getUsertype())){
			roles = roleinfoService.getAll();
		}
		// B.如果是其它管理员，则只能分配自己拥有的角色（注：非管理员无法访问）
		else{
			roles = roleinfoService.getByUser(logonUser.getPkUserinfo());
		}		
		map.addAttribute("roles", roles);		
		// (3)用户已拥有的角色
		List<Integer> rolePks = userinfoService.findOwnRolePks(pkUserinfo);
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (int i=0; i<rolePks.size(); i++) {
			sb.append(String.valueOf(rolePks.get(i)));
			if(i<rolePks.size()-1){
				sb.append(',');				
			}
		}
		sb.append(']');
		map.addAttribute("rolepks", sb.toString());
		return "/auth/allotrole";
	}
	
	/**
	 * 加载用户分配菜单数据
	 * @param pkUserinfo
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/allotmenu")
	public String loadAllotMenu(@RequestParam("pkUserinfo")int pkUserinfo,
			HttpSession session,
			ModelMap map) throws Exception{
		MgUserinfo logonUser = (MgUserinfo)session.getAttribute(AuthFilter.LOGON_USER);
		// (1)分配的用户对象本身
		MgUserinfo user = userinfoService.getByPk(pkUserinfo);
		map.addAttribute("user", user);
		// (2)系统现存的可分配的角色
		List<MgRoleinfo> roles;
		// A.如果是超级管理员，则可以分配所有的角色
		if("3".equals(logonUser.getUsertype())){
			roles = roleinfoService.getAll();
		}
		// B.如果是其它管理员，则只能分配自己拥有的角色（注：非管理员无法访问）
		else{
			roles = roleinfoService.getByUser(logonUser.getPkUserinfo());
		}		
		map.addAttribute("roles", roles);		
		// (3)用户已拥有的角色
		List<Integer> rolePks = userinfoService.findOwnRolePks(pkUserinfo);
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (int i=0; i<rolePks.size(); i++) {
			sb.append(String.valueOf(rolePks.get(i)));
			if(i<rolePks.size()-1){
				sb.append(',');				
			}
		}
		sb.append(']');
		map.addAttribute("rolepks", sb.toString());
		return "/auth/allotrole";
	}
	
	/**
	 * 保存用户分配角色数据
	 * @param pkUserinfo
	 * @param roles
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveallot")
	public String saveAllot(@RequestParam("pkUserinfo")int pkUserinfo, 
			@RequestParam(required=false,value="pkRoleinfo")int[] roles) throws Exception{
		if(roles == null)roles = new int[0];
		List<MgUserRole> urlist = new ArrayList<MgUserRole>(roles.length);
		for (int pkRoleinfo : roles) {
			MgUserRole ur = new MgUserRole();
			ur.setAdddatetime(DateHelp.dateTime());
			MgUserRoleId id = new MgUserRoleId();
			id.setPkRoleinfo(pkRoleinfo);
			id.setPkUserinfo(pkUserinfo);
			ur.setId(id);
			urlist.add(ur);			
		}		
		userinfoService.saveUserRole(pkUserinfo, urlist);
		return "redirect:/auth/user.do";
	}
	/************** ↑↑↑↑  用户分配资源  ↑↑↑↑ **************/
}
